package controllers

import (
	"encoding/json"
	"fmt"
	"github.com/astaxie/beego"
	"github.com/astaxie/beego/httplib"
	"github.com/astaxie/beego/orm"
	"gowe/models"
)

type MeController struct {
	beego.Controller
}

func (this *MeController) Get() {
	code := this.GetString("code")

	user := getToken(code)
	this.Data["nickName"] = user.NickName
	this.Data["headImgUrl"] = user.HeadImgUrl
	this.TplName = "me.tpl"
}

func getToken(code string) models.User {
	url := "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" + beego.AppConfig.String("AppId") + "&secret=" + beego.AppConfig.String("AppSecret") + "&code=" + code + "&grant_type=authorization_code"
	req := httplib.Get(url)
	str, err := req.String()
	if err != nil {
		beego.Error(err)
	}
	fmt.Println("token---->请求",str)
	//goAccessToken := &GoAccessToken{}
	goAccessToken := make(map[string]interface{})
	json.Unmarshal([]byte(str), &goAccessToken)
	token := goAccessToken["access_token"].(string)
	//if goAccessToken["access_token"] != nil {
		return getUserInfo(token)
	//}
}

func getUserInfo(token string) models.User {
	url := "https://api.weixin.qq.com/sns/userinfo?access_token=" + token + "&openid=" + beego.AppConfig.String("AppId") + "&lang=zh_CN"
	req := httplib.Get(url)
	str, err := req.String()
	if err != nil {
		beego.Error(err)
	}
	fmt.Println("用户数据------>",str)
	// 存储用户数据和token
	o := orm.NewOrm()
	var user models.User
	json.Unmarshal([]byte(str), &user)
	fmt.Println(user)
	id, err := o.Insert(&user)
	if err == nil {
		fmt.Println(id)
	}

	return user
}
